import 'package:flutter/material.dart';
import 'RepairItem.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../widgets/AppColors.dart';

class RepairPlanPage extends StatefulWidget {
  const RepairPlanPage({super.key});

  @override
  State<RepairPlanPage> createState() => _RepairPlanPageState();
}

class _RepairPlanPageState extends State<RepairPlanPage>
    with SingleTickerProviderStateMixin {
  final NetworkService _networkService = NetworkService();
  List<dynamic> dataList = [];

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          dataList = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.post(
        '/plcTimer/addressbook/selectAdressBookByDeptId?deptId=103',
      );
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('deptList Failed to load data');
      }
    } catch (e) {
      print('deptList Error in _fetchData: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('通讯录'),
        foregroundColor: AppColors.textPrimary,
        backgroundColor: Colors.transparent,
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        actions: [
          Container(
            color: const Color(0x4DFFFFFF),
            margin: const EdgeInsets.only(right: 16),
            padding: const EdgeInsets.only(top: 4, bottom: 4),
            // child: const Row(
            //   children: [
            //     // Image(image: AssetImage('assets/images/setting/check.png')),
            //     SizedBox(width: 8), // 添加间距
            //     Text('全部',
            //         style: TextStyle(fontSize: 16, color: Color(0xFF1D2129))),
            //     SizedBox(width: 8),
            //   ],
            // ),
          ),
        ],
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 列表
          Expanded(
            child: GridView.builder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, // 一排展示2个
                childAspectRatio: 1, // 可根据需要调整
              ),
              itemCount: dataList.length, // 数据条数
              physics: const NeverScrollableScrollPhysics(), // 禁止滚动

              itemBuilder: (context, index) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 0.0), // 设置行间距为1
                  child: GestureDetector(
                    // 添加点击事件
                    onTap: () {
                      // Navigator.push();
                    },
                    child: RepairItem(data: dataList[index]),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
